package com.company.base.common;

import java.io.UnsupportedEncodingException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.company.base.interceptor.AuthInterceptor;
import com.company.base.utils.CheckUtil;
import com.company.base.utils.WeChatUtil;
import com.company.site.mode.token.OatuhAccessToken;
import com.company.site.mode.wechatuser.OnlineUser;
import com.company.site.mode.wechatuser.WechatUser;
import com.company.site.user.UserService;

@Controller
@RequestMapping("oauth")
public class OAuthController{
	
	@Resource
	UserService userService;
	
	@RequestMapping("getCode")
	public String getCode(String resultUrl) {
		System.out.println("进入getCode方法！");
		return "redirect:https://open.weixin.qq.com/connect/oauth2/authorize?"
				+ "appid="+WeChatConstant.appId
				+ "&redirect_uri=http%3a%2f%2fwww.wbedc.com%2fwvote%2foauth%2fgetOpenIdByCode.htm"
				+ "&response_type=code"
				+ "&scope=snsapi_base"
				+ "&state="+resultUrl
				+ "#wechat_redirect";
	}
	@RequestMapping("getOpenIdByCode")
	public String getOpenIdByCode(HttpServletRequest request,String code,String state) throws UnsupportedEncodingException{
		System.out.println("进入getOpenIdByCode方法！");
		System.out.println("code："+code);
		System.out.println("resultUrl："+state);
		if(!CheckUtil.isEmpty(code)){
			//执行code换取openid
		    System.out.println(code);
			OatuhAccessToken accessToken=WeChatUtil.getOauthAccessToken(code);
			HttpSession session=request.getSession();
			session.setAttribute("openid", accessToken.getOpenid());
			//判断
			System.out.println("openid放入session中++++++++++++++++++++++++++++++++++++++++++++++++++");
			WechatUser w=userService.getUserInfoByOpenid(accessToken.getOpenid());
			if (CheckUtil.isEmpty(w)) {
				//存入数据库中，并且自动登录
				System.out.println("注册微信用户！");
					userService.subscribeUser(accessToken.getOpenid(),request);
					System.out.println("注册微信用户完毕！");
			}
			WechatUser wechatUserWechat=userService.getUserInfoByOpenid(accessToken.getOpenid());
			//自动登录
			session.setMaxInactiveInterval(30*60); //登录有效时间为30分钟
			OnlineUser onlineUser = new OnlineUser();
			onlineUser.setUserInfo(wechatUserWechat);
			session.setAttribute(AuthInterceptor.OPERATOR, onlineUser);
			// session保存用户登陆信息userInfoSession
			session.setAttribute("userInfoSession", wechatUserWechat);
		}
		System.out.println("+++  redirect:state  +++");
		System.out.println(state);
		return "redirect:"+state;
	}
}
